<template>
  <div class="callee">
    <div class="videos">
      <video controls="controls" ref="video1" class="video" />
      <video controls="controls" ref="video" class="video" />
    </div>
  </div>
</template>
<script>
import { createPeerConnection, getUserMediaSource } from '../function.js';
import { from, merge } from 'rxjs';
import { filter, tap, map, switchMap } from 'rxjs/operators';
export default {
  props: ['subject'],
  created() {
    const next = params => {
      this.subject.next({ ins: this, params });
    };
    const source = this.subject.pipe(filter(val => val.ins !== this));
    source
      .pipe(
        filter(val => val.params instanceof RTCSessionDescription),
        switchMap(val => {
          const peerConnection = createPeerConnection();
          const desc = new RTCSessionDescription(val.params);
          return merge(
            peerConnection.trackSource.pipe(
              map(val => val[0].streams[0]),
              tap(stream => {
                const video = this.$refs.video1;
                video.srcObject = stream;
                video.play();
              }),
            ),
            from(peerConnection.setRemoteDescription(desc)).pipe(
              switchMap(() => getUserMediaSource({ video: true })),
              tap(stream => {
                const video = this.$refs.video;
                video.srcObject = stream;
                video.play();
                peerConnection.addStream(stream);
              }),
              switchMap(() => peerConnection.createAnswer()),
              switchMap(val => from(peerConnection.setLocalDescription(val))),
              tap(() => next(peerConnection.localDescription)),
              switchMap(() => peerConnection.candidateSource),
              map(arr => arr[0]),
              tap(event => next(event.candidate)),
            ),
            source.pipe(
              filter(val => val.params instanceof RTCIceCandidate),
              tap(val => {
                const candidate = new RTCIceCandidate(val.params);
                peerConnection.addIceCandidate(candidate);
              }),
            ),
          );
        }),
      )
      .subscribe();
  },
};
</script>
<style lang="scss" scoped>
.callee {
  display: flex;
  flex-direction: column;
  padding: 20px;
  .videos {
    display: flex;
    .video {
      height: 200px;
      width: 400px;
    }
  }
}</style
>>
